package com.aoip.telemetry.telemetry.configureui.framework.web.service;

import javax.annotation.Resource;

import com.aoip.telemetry.telemetry.configureui.common.constant.Constants;
import com.aoip.telemetry.telemetry.configureui.common.core.domain.entity.SysRole;
import com.aoip.telemetry.telemetry.configureui.common.core.domain.entity.SysUser;
import com.aoip.telemetry.telemetry.configureui.common.core.domain.model.LoginUser;
import com.aoip.telemetry.telemetry.configureui.common.exception.ServiceException;
import com.aoip.telemetry.telemetry.configureui.common.exception.user.CaptchaException;
import com.aoip.telemetry.telemetry.configureui.common.exception.user.CaptchaExpireException;
import com.aoip.telemetry.telemetry.configureui.common.exception.user.UserPasswordNotMatchException;
import com.aoip.telemetry.telemetry.configureui.common.utils.DateUtils;
import com.aoip.telemetry.telemetry.configureui.common.utils.MessageUtils;
import com.aoip.telemetry.telemetry.configureui.common.utils.ServletUtils;
import com.aoip.telemetry.telemetry.configureui.common.utils.ip.IpUtils;
import com.aoip.telemetry.telemetry.configureui.framework.config.properties.CasProperties;
import com.aoip.telemetry.telemetry.configureui.framework.security.manager.AsyncManager;
import com.aoip.telemetry.telemetry.configureui.framework.security.manager.factory.AsyncFactory;
import com.aoip.telemetry.telemetry.configureui.system.service.ISysConfigService;
import com.aoip.telemetry.telemetry.configureui.system.service.ISysUserService;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 登录校验方法
 * 
 * @author ss
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private CasProperties casProperties;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff)
        {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 登录验证
     * @param attributes
     * @return 结果
     */
    public String loginCas(Map attributes)
    {
        // 用户验证
        Authentication authentication;
        String userCode = (String) attributes.get("userCode");
        SysRole role=userService.getRole(userCode,casProperties.getRoleId());
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            String lname=casProperties.getUserName();
            String lpwd=casProperties.getPwd();
            if(role!=null && role.getRoleId()==2){
                lname=casProperties.getUserName2();
                lpwd=casProperties.getPwd2();
            }
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(lname, lpwd));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(casProperties.getUserName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(casProperties.getUserName(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        //String userCode = (String) attributes.get("userCode");
        String userName = (String) attributes.get("userName");
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser user=loginUser.getUser();
        user.setUserName(userName);
        //List<SysRole> roles=new ArrayList<SysRole>();
        //SysRole role=userService.getRole(userCode,casProperties.getRoleId());
       // roles.add(role);
       //user.setRoles(roles);
        recordLoginInfo(user);
        // 生成token
        loginUser.setUser(user);
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserLogin(user);
    }
}
